#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
最终诊断脚本 - 彻底解决认证问题
"""

import requests
import sys
import os
import time
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from backend.app import create_app
from flask import request, g
import threading

def create_diagnostic_app():
    """创建诊断版本的Flask应用"""
    app = create_app()
    
    # 强制添加请求日志
    @app.before_request
    def force_log_request():
        print(f"\n>>> BEFORE_REQUEST <<<")
        print(f"时间: {time.strftime('%Y-%m-%d %H:%M:%S')}")
        print(f"方法: {request.method}")
        print(f"路径: {request.path}")
        print(f"端点: {request.endpoint}")
        print(f"Authorization: {request.headers.get('Authorization', 'None')}")
        print(f"User-Agent: {request.headers.get('User-Agent', 'None')}")
        print(f"g对象: {vars(g)}")
        
        # 检查路由匹配
        if request.endpoint:
            view_func = app.view_functions.get(request.endpoint)
            if view_func:
                print(f"视图函数: {view_func.__name__}")
                print(f"是否有装饰器: {hasattr(view_func, '__wrapped__')}")
        print(f">>> END BEFORE_REQUEST <<<\n")
    
    @app.after_request
    def force_log_response(response):
        print(f"\n>>> AFTER_REQUEST <<<")
        print(f"状态码: {response.status_code}")
        print(f"内容类型: {response.content_type}")
        print(f"内容长度: {response.content_length}")
        print(f">>> END AFTER_REQUEST <<<\n")
        return response
    
    return app

def run_diagnostic_server():
    """运行诊断服务器"""
    print("=== 启动诊断服务器 (端口5002) ===")
    app = create_diagnostic_app()
    app.run(host='127.0.0.1', port=5002, debug=False, use_reloader=False)

def test_both_servers():
    """测试两个服务器"""
    test_path = '/api/netdisk/download/43/bb/43bb0dd030fe6beb70e92fdce9b1e560.mp4'
    
    print("\n=== 测试端口5000服务器 ===")
    try:
        response = requests.head(f"http://127.0.0.1:5000{test_path}", timeout=5)
        print(f"端口5000状态码: {response.status_code}")
        print(f"端口5000响应头: {dict(response.headers)}")
    except Exception as e:
        print(f"端口5000测试失败: {e}")
    
    print("\n=== 测试端口5002服务器 ===")
    try:
        response = requests.head(f"http://127.0.0.1:5002{test_path}", timeout=5)
        print(f"端口5002状态码: {response.status_code}")
        print(f"端口5002响应头: {dict(response.headers)}")
    except Exception as e:
        print(f"端口5002测试失败: {e}")

def check_file_system():
    """检查文件系统中是否存在静态文件服务"""
    print("\n=== 检查文件系统 ===")
    
    # 检查是否有静态文件配置
    app = create_app()
    print(f"静态文件夹: {app.static_folder}")
    print(f"静态URL路径: {app.static_url_path}")
    
    # 检查蓝图的静态文件配置
    for name, blueprint in app.blueprints.items():
        if hasattr(blueprint, 'static_folder') and blueprint.static_folder:
            print(f"蓝图 {name} 静态文件夹: {blueprint.static_folder}")
        if hasattr(blueprint, 'static_url_path') and blueprint.static_url_path:
            print(f"蓝图 {name} 静态URL路径: {blueprint.static_url_path}")
    
    # 检查文件是否真实存在
    file_path = "uploads/43/bb/43bb0dd030fe6beb70e92fdce9b1e560.mp4"
    full_path = os.path.join(os.getcwd(), file_path)
    print(f"\n检查文件: {full_path}")
    print(f"文件存在: {os.path.exists(full_path)}")
    if os.path.exists(full_path):
        print(f"文件大小: {os.path.getsize(full_path)} bytes")

def check_nginx_or_proxy():
    """检查是否有Nginx或其他代理"""
    print("\n=== 检查代理服务 ===")
    
    # 检查响应头中的服务器信息
    try:
        response = requests.head("http://127.0.0.1:5000/api/netdisk/download/43/bb/43bb0dd030fe6beb70e92fdce9b1e560.mp4", timeout=5)
        server_header = response.headers.get('Server', 'Unknown')
        print(f"服务器头: {server_header}")
        
        # 检查是否有代理相关的头
        proxy_headers = ['X-Forwarded-For', 'X-Real-IP', 'X-Forwarded-Proto', 'Via']
        for header in proxy_headers:
            value = response.headers.get(header)
            if value:
                print(f"代理头 {header}: {value}")
        
        # 检查所有响应头
        print("\n所有响应头:")
        for key, value in response.headers.items():
            print(f"  {key}: {value}")
            
    except Exception as e:
        print(f"检查代理失败: {e}")

if __name__ == '__main__':
    print("=== 最终诊断开始 ===")
    
    # 1. 检查文件系统
    check_file_system()
    
    # 2. 检查代理
    check_nginx_or_proxy()
    
    # 3. 启动诊断服务器
    server_thread = threading.Thread(target=run_diagnostic_server)
    server_thread.daemon = True
    server_thread.start()
    
    # 等待服务器启动
    time.sleep(3)
    
    # 4. 测试两个服务器
    test_both_servers()
    
    print("\n=== 诊断完成 ===")
    time.sleep(2)